package com.ruoyi.quartz.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component("wxAccessTokenTask")
public class WxAccessTokenTask {
    private static final  String url = "https://api.weixin.qq.com/cgi-bin/token";
    private static final  String lockKey = "wx:xiaoChengXu:lock";
    private static final  String cacheKey = "wx:xiaoChengXu:access_token";

    @Autowired
    private  StringRedisTemplate stringRedisTemplate;

    /**
     * 定时获取微信小程序accessToken 并存入redids库
     */
    public void wxAccessTokenTask()
    {
        //分布式锁防止刷新缓存时操作数据
        String lockValue = UUID.randomUUID().toString().replace("-","");
        try {
        stringRedisTemplate.opsForValue().set(lockKey,lockValue,1,TimeUnit.SECONDS);
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("grant_type", "client_credential");
            map.put("appid", "wx86ad7950e07218a5");// 改成自己的appid
            map.put("secret", "50474d912f1b9e3ebcdc5605e13df955"); //改成自己的secret
            String rt = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", map);
            JSONObject json = JSONObject.parseObject(rt);
            String accessToken = json.getString("access_token");
            if (accessToken != null && accessToken != "") {
                stringRedisTemplate.opsForValue().set( cacheKey, accessToken, 90, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            throw new RuntimeException("获取 AccessToken 失败: " + e.getMessage());
        } finally {
            // 释放锁（需原子操作）
            if (lockValue.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                stringRedisTemplate.delete(lockKey);
            }
        }


    }
}
